package com.huizluo.module4.UserMessage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        ObjectInputStream or = null;
        ObjectOutputStream op = null;
        try{
            ss = new ServerSocket(8888);
            System.out.println("waiting client connect...");

            s = ss.accept();
            System.out.println("client connected");

            while (true){
                UserMessage msg = null;
                try{
                    or = new ObjectInputStream(s.getInputStream());
                    msg = (UserMessage) or.readObject();

                    System.out.println(msg);

                    if (msg.getUser().Auth()){
                        msg.setType("success");
                    }else{
                        msg.setType("fail");
                    }

                    op = new ObjectOutputStream(s.getOutputStream());

                    op.writeObject(msg);
                }catch (IOException e){
                    break;
                }catch (ClassNotFoundException e){
                    break;
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        } finally {
            if (or != null){
                try {
                    or.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (op != null){
                try {
                    op.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != s){
                try {
                    s.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

            if (null != ss){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
